﻿// Copyright © 2012 X-treem Software Limited
// Adapted from WPF AutoComplete TextBox Control by Jason Payne
// Licence: http://wpfgooglesearch.codeplex.com/license
// Credit: http://wpfactb.codeplex.com

using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Xml.Linq;

namespace Xtreem.GoogleSearch.AutoSuggest
{
    internal class GoogleSuggestionProvider : IAutoSuggestDataProvider
    {
        public IEnumerable<TextBlock> GetSuggestions(string searchString)
        {
            var doc = XDocument.Load("http://google.com/complete/search?output=toolbar&q=" + searchString);

            return doc.Descendants("CompleteSuggestion").Select(x =>
                {
                    string suggestion = x.Element("suggestion").Attribute("data").Value.ToLowerInvariant();
                    searchString = searchString.ToLowerInvariant();
                    var tb = new TextBlock();

                    if (suggestion.StartsWith(searchString))
                    {
                        tb.Inlines.Add(new Run(searchString));
                        tb.Inlines.Add(new Bold(new Run(suggestion.Remove(0, searchString.Length))));
                    }
                    else
                    {
                        tb.Inlines.Add(new Bold(new Run(suggestion)));
                    }

                    return tb;
                });
        }
    }
}
